package com.atguigu.gulimall.ware.service.impl;

import cn.hutool.json.JSONUtil;
import com.atguigu.common.utils.PageUtils;
import com.atguigu.common.utils.Query;
import com.atguigu.common.utils.R;
import com.atguigu.gulimall.ware.dao.WareInfoDao;
import com.atguigu.gulimall.ware.entity.WareInfoEntity;
import com.atguigu.gulimall.ware.feign.MemberFeignService;
import com.atguigu.gulimall.ware.service.WareInfoService;
import com.atguigu.gulimall.ware.vo.FareVo;
import com.atguigu.gulimall.ware.vo.MemberAddressVo;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.Map;


@Service("wareInfoService")
public class WareInfoServiceImpl extends ServiceImpl<WareInfoDao, WareInfoEntity> implements WareInfoService {

    @Resource
    private MemberFeignService memberFeignService;

    @Override
    public PageUtils queryPageByCondition(Map<String, Object> params) {

        String key = (String) params.get("key");
        LambdaQueryWrapper<WareInfoEntity> wrapper = new LambdaQueryWrapper<>();
        wrapper.and(StringUtils.hasText(key), w -> w.eq(WareInfoEntity::getId, key)
                .or().like(WareInfoEntity::getName, key)
                .or().like(WareInfoEntity::getAddress, key)
                .or().like(WareInfoEntity::getAreacode, key));

        IPage<WareInfoEntity> page = this.page(new Query<WareInfoEntity>().getPage(params), wrapper);

        return new PageUtils(page);
    }

    @Override
    public FareVo getFare(Long addrId) {
        FareVo fareVo = new FareVo();
        R r = memberFeignService.getReceiveAddressInfo(addrId);
        if (r.getCode() == 0) {
            Object data = r.get("memberReceiveAddress");
            MemberAddressVo memberAddressVo = JSONUtil.toBean(JSONUtil.toJsonStr(data), MemberAddressVo.class);
            if (memberAddressVo != null) {
                // 调用物流公司接口，查询运费
                // 这里简单处理，以用户手机号最后一位作为运费
                BigDecimal fare = new BigDecimal(memberAddressVo.getPhone().substring(memberAddressVo.getPhone().length() - 1));
                fareVo.setAddress(memberAddressVo);
                fareVo.setFare(fare);
                return fareVo;
            }
        }
        return null;
    }

}